﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace BDRUtils.Utility
{
    public class HttpUtility
    {
        private const int timeout = 30;
        private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            return true;
        }

        /// <summary>
        /// Post异步请求
        /// </summary>
        /// <param name="url">请求url</param>
        /// <param name="content">请求body内容</param>
        /// <param name="timeout">超时时间</param>
        /// <param name="headers">请求头</param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> PostAsync(string url, string content = "", int timeout = timeout, Dictionary<string, string> headers = null)
        {
            HttpResponseMessage response = null;
            try
            {
                using (var handler = new HttpClientHandler())
                {
                    handler.ServerCertificateCustomValidationCallback += RemoteCertificateValidate;
                    using (HttpClient Client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(timeout) })
                    {
                        var buffer = Encoding.UTF8.GetBytes(content);
                        using (var byteContent = new ByteArrayContent(buffer))
                        {
                            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                            if (headers == null) headers = new Dictionary<string, string>();
                            if (headers != null && headers.Count != 0)
                            {
                                foreach (var item in headers)
                                {
                                    Client.DefaultRequestHeaders.Add(item.Key, item.Value);
                                }

                            }
                            response = await Client.PostAsync(url, byteContent);
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("错误信息1：" + ex.Message);
                if (ex.Response != null)
                {
                    string responseContent = string.Empty;
                    using (var strStream = ex.Response.GetResponseStream())
                    {
                        using (var sr = new StreamReader(strStream))
                        {
                            responseContent = sr.ReadToEnd();
                        }
                    }
                    if (responseContent.Length > 0)
                    {
                        throw new System.Exception($"response :{responseContent}", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("错误信息2：" + ex.Message);
                return null;
            }
            return response;

        }

        /// <summary>
        /// Get异步请求
        /// </summary>
        /// <param name="url">请求url</param>
        /// <param name="headers">请求头</param>
        /// <param name="timeout">超时时间</param>
        /// <param name="secret">秘钥</param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> GetAsync(string url, Dictionary<string, string> headers = null, int timeout = timeout, string secret = "")
        {
            HttpResponseMessage response = null;
            try
            {
                using (var handler = new HttpClientHandler())
                {
                    handler.ServerCertificateCustomValidationCallback += RemoteCertificateValidate;
                    using (HttpClient Client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(timeout) })
                    {
                        if (headers == null) headers = new Dictionary<string, string>();
                        if (headers != null)
                        {
                            foreach (var header in headers)
                            {
                                Client.DefaultRequestHeaders.Add(header.Key, header.Value);
                            }
                        }
                        if (!string.IsNullOrEmpty(secret))
                        {
                            Client.DefaultRequestHeaders.Add("USBKeyNOAndUserCodeAndDate", secret);
                        }
                        response = await Client.GetAsync(url);
                    }
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("错误信息1：" + ex.Message);
                if (ex.Response != null)
                {
                    string responseContent = string.Empty;
                    using (var strStream = ex.Response.GetResponseStream())
                    {
                        using (var sr = new StreamReader(strStream))
                        {
                            responseContent = sr.ReadToEnd();
                        }
                    }
                    if (responseContent.Length > 0)
                    {
                        throw new System.Exception($"response :{responseContent}", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("错误信息2：" + ex.Message);
                return null;
            }

            return response;
        }
    }
}
